import React, {Component} from 'react'
import {browserHistory} from 'react-router';
import cookie from 'react-cookie';
import {Modal} from 'antd';
import $ from 'jquery'

import styles from './index.scss';

export default class Login extends Component {

    constructor(props) {
        super(props);
        this.state = {
            userName: "",
            userPassword: "",
            isRemember: false,
            modalIsOpen: false,
            loginLoading: '登录',
            languagetype: true //语言切换，true为中文，false为英文
        };
    }

    componentDidMount() {
        // let userId = cookie.load('userId'); let userPwd = cookie.load('userPwd'); if
        // (userId && userPwd){    //  window.location.hash = '/main'
        // browserHistory.push('/main'); }
        if (window.localStorage.getItem('language') == 'EN') {
            this.setState({
                languagetype:false
            });
        } else {
            window.localStorage.setItem('language', 'CH');
            this.setState({
                languagetype:true 
            });
        }
    }

    //获取操作权限
    fetchPerms = () => {
        window.localStorage.setItem('permissions','');
        $.ajax({
            url: ' /base/auth/perms',
            type: 'post',
            dataType: 'json',
            data: {}
        }).done(function (data, status, xhr) {
                if (data.code == "1") {
                    window.localStorage.setItem('permissions',data.data.permissions);
                } else {
                    console.log("失败：", data.msg);
                }
            }.bind(this));
    }

    changeUsername = (e) => {
        let uname = e.target.value;
        this.setState({userName: uname});
    };
    changePassword = (e) => {
        let upwd = e.target.value;
        this.setState({userPassword: upwd})
    };
    //是否记住密码
    handleCheckbox = (e) => {
        let isChecked = e.target.checked;
        if (isChecked) {
            this.setState({isRemember: true})
        } else {
            this.setState({isRemember: false})
        }
    };
    isHandleClick = (e) => {
        if (e.keyCode == 13) {
            this.handleClick();
        }
    };

    // 密码过于简单的提示信息
    showEditPwdHandle = (_this) => {
        Modal.warning({
            title: '密码警告',
            content: (
              <div>
                <p>请进入系统后修改您的密码！</p>
              </div>
            ),
            onOk() {
                _this.setState({
                    loginLoading: '登录'
                })
                browserHistory.push('/main');
            },
          });
    }

    handleClick = () => {
        //提交表单 成功后进行跳转
        if (this.state.userName === "" || this.state.userName === null) {
            Modal.info({
                title: "提示",
                content: "账号不能为空"
            });
        } else if (this.state.userPassword === "" || this.state.userPassword === null) {
            Modal.info({
                title: "提示",
                content: "密码不能为空"
            });
        } else {

            if (this.state.isRemember === true) { //是否记住密码，若记住，则保存至localstorage，反之，清除
                // let loginData = {}; loginData.userName = this.state.userName;
                // loginData.userPassword = this.state.userPassword; let d=new Date();
                // d.setDate(d.getDate()+30);
                //
                // cookie.save('userId', loginData.userName, { path: '/', expires:d });
                // cookie.save('userPwd', loginData.userPassword, { path: '/', expires:d });

            } else {
                //Data.localRemoveItem("jiaj-loginStatus");

            }
            //this.state.userName   userPassword
            this.setState({
                loginLoading: '登录中'
            });
            window.localStorage.setItem('gongc','')
            let _this=this;
            $.ajax({
                url: '/base/auth/login',
                type: 'post',
                dataType: 'json',
                data: {
                    username: this.state.userName,
                    password: this.state.userPassword
                }
            })
                .done(function (data, status, xhr) {
                    //console.log("----------",  JSON.stringify(data, null, 4));
                    if (data.code == "1") {
                        if(data.data=='pwd'){
                            this.showEditPwdHandle(_this);
                            
                        }else{
                            this.setState({
                                loginLoading: '登录'
                            });
                            this.fetchPerms();
                            // window.isLogin = true;
                            browserHistory.push('/main');
                        }
                    } else {
                        console.log("失败：", data.msg);

                        this.setState({
                            loginLoading: '登录'
                        });
                        Modal.error({
                            title: "登录错误",
                            content: data.msg
                        });
                    }
                }.bind(this));
        }
    };

    languageClick = () => {
        if (this.state.languagetype) {
            this.setState({
                languagetype: false
            });
            window.localStorage.setItem('language', 'EN');
        } else {
            this.setState({
                languagetype: true
            });
            window.localStorage.setItem('language', 'CN');
        }
    }

    render() {
        return (
            <div className={styles.loginPage}>
                <div className={styles.loginBox}>
                    <form action="" className={styles.horizontal} onKeyDown={this.isHandleClick}>
                        <div className={styles.loginTop} onClick={this.languageClick}>
                            {/* <span className={this.state.languagetype ? styles.changeLanguage : styles.changeLanguageEn}>语言切换</span> */}
                        </div>
                        <div className={styles.logo}>
                        {/* <span className={styles.logoPng}></span> */}
                        <span className={styles.logoText}>
                        嘉兴鹏海智能制造WMS系统软件
                        </span>
                        </div>
                        <input
                            type="text"
                            className={styles.oInput}
                            name="username"
                            id="uname"
                            ref="uname"
                            placeholder="用户名"
                            onChange={this.changeUsername}/>
                        <input
                            type="password"
                            className={styles.oInput}
                            name="password"
                            id="upwd"
                            ref="upwd"
                            placeholder="请输入您的密码"
                            onChange={this.changePassword}/>
                        <div className={styles.rememberPwd}>
                            {/*<input type="checkbox"  id="chk" className={styles.checkbox} checked={this.state.isRemember} onClick={this.handleCheckbox.bind(this)} />*/}
                            {/*<label className={styles.cbTxt} htmlFor="chk">记住账号</label>*/}
                            {/* <span className={styles.forgetPwd}>忘记密码？</span> */}
                        </div>
                        <input
                            type="button"
                            className={styles.loginBtn}
                            value={this.state.loginLoading}
                            onClick={this.handleClick}/>
                        <p className={styles.p}>Copyright ©2018 Powered By JiaXingPengHai</p>
                        <p className={styles.p}>Version 1.0.0</p>
                        {/* <div className={styles.p}>
                        <a className={styles.p} href="http://esp.haier.com/dispatcher?stamp=25643256&action=msg.create&state=step2&custom_prd_id=qq_COSMOWMS&msgcontent=&msg_class=10&comp=qq&project_no=COSMOWMS&main_typecode=10&outCreateFlag=0/">问题反馈请登录ESP创建消息到COSMOPlat</a>
                        </div> */}
                    </form>
                </div>
            </div>
        );
    }
};
